import java.util.List;
import java.util.Random;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.runtime.Execution;
import org.apache.log4j.Logger;

public class IEFinish implements JavaDelegate {
	private static Logger logger = Logger.getLogger("IEFinish");

	@Override
	public void execute(DelegateExecution arg0) throws Exception {
		logger.info(arg0.getProcessInstanceId() + " " + arg0.getId());
		String processId = (String) arg0.getVariable("processId");
		// int orderNum = (Integer) arg0.getVariable("orderNum");
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		RuntimeService runtimeService = processEngine.getRuntimeService();
		int completeIECount = (Integer) runtimeService.getVariable(processId, "completeIECount");
		int iECount = (Integer) runtimeService.getVariable(processId, "IEcount");
		completeIECount++;
		runtimeService.setVariable(processId, "completeIECount", completeIECount);

		if (completeIECount == iECount) {
			Execution execution = runtimeService.createExecutionQuery().processInstanceId(processId).activityId("IEcomplete").singleResult();
			if (execution != null) {
				logger.info("All IE are complete, sending signal to continue");
				runtimeService.signal(execution.getId());
			} else {
				logger.error("Process with id: " + processId + " and with activity: IEcomplete not found");
			}
		}
		
		// signal
		// for (int i = 0; i < 30; i++) {
		// ProcessEngine processEngine =
		// ProcessEngines.getDefaultProcessEngine();
		// RuntimeService runtimeService = processEngine.getRuntimeService();
		// Execution execution = getOneSubscriber(runtimeService, processId);
		// if (execution != null) {
		// runtimeService.signalEventReceived("catchSignal", execution.getId());
		// logger.info("signal send");
		// break;
		// } else {
		// logger.info("sleep");
		// Thread.sleep(new Random().nextInt(10000));
		// }
		// }

	

	}

	private Execution getOneSubscriber(RuntimeService runtimeService, String processId) {
		List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processId).signalEventSubscriptionName("catchSignal")
				.list();
		if (executions.size() > 0) {
			logger.info("executions.size() " + executions.size());
			return executions.get(0);
		}
		return null;

	}

}
